package com.hoyue.dao.impl;

import java.sql.SQLException;

import java.util.List;

import com.hoyue.bean.Character;
import com.hoyue.dao.CharacterDao;
import com.hoyue.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

public class CharacterDaoImpl implements CharacterDao {
    QueryRunner qr = C3P0Utils.getQueryRunner();

    @Override
    public void addChar(Character character) throws SQLException {
        String sql = "insert into character_p(id,number,name,slogan,picture_address)values(?,?,?,?,?)";
        qr.update(sql, character.getId(), character.getNumber(), character.getName(), character.getSlogan(), character.getPicture_address());
    }

    @Override
    public void deleteChar(int id) throws SQLException {
        String sql = "delete from character_p where id=?";
        qr.update(sql, id);
    }

    @Override
    public Character findById(int id) throws SQLException {
        return null;
    }

    @Override
    public void updateChar(Character character) throws SQLException {
        String sql = "update character_p set number = ? , name = ? , slogan = ? , picture_address = ? where id = ?";

        qr.update(sql,character.getNumber(),character.getName(),character.getSlogan(),character.getPicture_address(),character.getId());
    }

    @Override
    public List<Character> getAllChar() throws SQLException {
        String sql = "select * from character_p";

        return qr.query(sql,new BeanListHandler<>(Character.class));
    }
    @Override
    public Character getCharacterById(String id) throws SQLException {
        String sql = "select * from character_p where id = " + id;
        return qr.query(sql,new BeanHandler<>(Character.class));
    }

    @Override
    public String getAddressById(int id) throws SQLException {
        String sql = "SELECT picture_address FROM character_p WHERE id=?";

        return qr.query(sql,new ScalarHandler<>(),id);
    }
}
